//
//  YZMyStocksAddViewController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/31.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMyStocksAddViewController.h"
#import "YZMAppStyle.h"
#import "YZMyStocksSearchCell.h"
#import "YZMStockSearchService.h"
#import "YZMyStocksService.h"
#import "YZMStockInfo.h"
#import "YZMStockViewController.h"
#import "UIViewController+Utils.h"
#import "YZMAlertView.h"
#import <Masonry/Masonry.h>
#import "YZMTradeTypeDef.h"
#import "YZMOneyuanViewController.h"
#import "YZMSimulateViewController.h"
#import "YZMFreeExperienceViewController.h"
#import "WclKeyBoardView.h"
#import "SwitchKeyBoardView.h"

NSString *const sYZMyStocksSearchCellID = @"YZMyStocksSearchCellID";

@interface YZMyStocksAddViewController()<UITableViewDataSource, UITableViewDelegate,WclKeyBoardViewDelegate,SwitchKeyBoardViewDelegate>

@property (nonatomic, strong) UITextField *searchField;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataList;
@property (nonatomic, strong) UIView *clearView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, assign) BOOL isHistoryRecordFlag;
@property (nonatomic, assign) YZM_TRADE_TYPE tradeType;

@property (nonatomic, strong) NSDictionary *param;

@property (nonatomic, strong) WclKeyBoardView *keyBoardView;

@property (nonatomic, strong) SwitchKeyBoardView *switchKeyBoardView;

@property (nonatomic, strong) UIView *inputView;

@property (nonatomic, strong) NSMutableString *searchString;

@end

@implementation YZMyStocksAddViewController

- (instancetype)init{
    
    self = [super init];
    if (self) {
        self.searchString = [NSMutableString string];
        self.hidesBottomBarWhenPushed = YES;
         [[YZMStockSearchService sharedService] checkIfNeedUpdateStocks];
    }
    return self;
}

- (void)viewDidLoad{
    
    [super viewDidLoad];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    self.navigationItem.hidesBackButton = YES;
    
    [self createObjects];
    [self registerForKeyboardAutoWithBottomView:_bottomView andGestureFlag:NO];
    [self textValueChanged:nil];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.searchField becomeFirstResponder];
}

- (void)resignFirstResponderAll{
    
    [self.view endEditing:YES];
}

#pragma mark -- event

- (void)clearButtonPressed: (id)sender
{
    [self.searchField resignFirstResponder];
    __weak typeof(&*self) safeSelf = self;
    YZMAlertView *alert = [YZMAlertView alertViewForRecommandWithContent:@"删除搜索历史记录？"];
    alert.cancelButton.hidden = NO;
    alert.confirmHandle = ^(){
        [[YZMStockSearchService sharedService] clearHistory];
        if (safeSelf.searchField.text.length == 0) {
            safeSelf.dataList = nil;
            safeSelf.tableView.tableFooterView = nil;
            [safeSelf.tableView reloadData];
        }
        return YES;
    };
    [alert show];
}

- (void)cancelButtonPressed:(UIButton *)sender{
    [self.searchField resignFirstResponder];
    [YZMHCMInstance popViewController];
}

- (void)textValueChanged:(UITextField *)textField{
    NSString *searchStr;
    if (textField.text.length == 0) {
        searchStr = @"";
    }else{
        searchStr = textField.text;
    }
    self.searchString = [NSMutableString stringWithString:searchStr];
    [self searchString:self.searchString];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (self.dataList.count == 0) {
        
        return 0;
    }
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if(self.dataList.count == 0) return [UIView new];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
    view.backgroundColor = [YZMAppStyle colorForMain];
    
    UILabel *label = [YZMAppStyle labelWithMediumWhite];
    label.text = self.isHistoryRecordFlag?@"以下为历史查询记录": @"以下为查询记录";
    [view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(view);
        make.left.equalTo(view).offset(15);
    }];
    
    UIView *splitLine = [YZMAppStyle splitLine];
    [view addSubview:splitLine];
    [splitLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(view);
    }];
    
    return view;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YZMyStocksSearchCell *cell = [tableView dequeueReusableCellWithIdentifier: sYZMyStocksSearchCellID  forIndexPath:indexPath];
    
    NSInteger row = indexPath.row;
    if (row < self.dataList.count) {
        
        YZMStockInfo *stock = self.dataList[row];
        cell.record = stock;
        YZMIndexCount indexCount;
        indexCount.index = indexPath.row == 0?1:indexPath.row;
        indexCount.count = self.dataList.count;
        cell.indexCount = indexCount;
        cell.operAction = ^(YZMStockInfo *stock, BOOL addFlag){
          
           return [[YZMyStocksService sharedService] operationStock:stock withAddFlag:addFlag];
        };
    }
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 54.0;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row < self.dataList.count) {
        YZMStockInfo *info = self.dataList[indexPath.row];
        if (info.code.length == 0) {
            return;
        }
        [self.searchField resignFirstResponder];
        [[YZMStockSearchService sharedService] appendHistoryWithCode:info.code];
        self.searchField.text = nil;
        NSDictionary *param = nil;
        if (info.name.length == 0) {
            param = @{@"stockcode": info.code};
        }
        else
        {
            param = @{@"stockcode": info.code, @"stockname": info.name};
        }
        
        YZMStockViewController *tradeVC = nil;
        YZMOneyuanViewController *oneVC=nil;
        YZMSimulateViewController *simVC=nil;
        YZMFreeExperienceViewController *freeVc = nil;
        
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"UpdateCurrentIndex" object:nil userInfo:@{@"currentIndex":@(0)}];
        
        switch (self.tradeType) {
            case YZM_TRADE_TYPE_FOR_A_STOCK:
            case YZM_TRADE_TYPE_FOR_A_STOCK_YLB:
            {
                if ([self.param.allKeys containsObject:@"page"]) {
                    if ([self.param[@"page"] isEqualToString:@"next"]) {
                        YZMStockInfo *stock = [self.dataList objectAtIndex: indexPath.row];
                        if (stock.code.length == 0) {
                            return;
                        }
                        NSDictionary *param = nil;
                        if (stock.name.length == 0) {
                            param = @{@"stockcode": stock.code};
                        }
                        else
                        {
                            param = @{@"stockcode": stock.code, @"stockname": stock.name};
                        }
                        [[YZMStockSearchService sharedService] appendHistoryWithCode:stock.code];
                        if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
                            [YZMHCMInstance pushViewControllerWithName: @"stockYLB" andParams: param];
                            return;
                        }
                        [YZMHCMInstance pushViewControllerWithName: @"stock" andParams: param];
                        return;
                    }
                }
                if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
                     tradeVC = [YZMHCMInstance instanceWithControllerName:@"stockYLB"];
                }else{
                    tradeVC = [YZMHCMInstance instanceWithControllerName:@"stock"];
                }
                [tradeVC updateWithParamsManual:param];
                [YZMHCMInstance popViewController:tradeVC animated:YES];
            }
                break;
                
            case YZM_TRADE_TYPE_FOR_A_STOCK_D: {
                tradeVC = [YZMHCMInstance instanceWithControllerName:@"stockTD"];
                [tradeVC updateWithParamsManual:param];
                [YZMHCMInstance popViewController:tradeVC animated:YES];
            }
                break;
                
            case YZM_TRADE_TYPE_FOR_A_STOCK_ONE:{
                oneVC = [YZMHCMInstance instanceWithControllerName:@"oneYuan"];
                [oneVC updateWithParamsManual:param];
                [YZMHCMInstance popViewController:oneVC animated:YES];
            }
                break;
            case YZM_TRADE_TYPE_FOR_A_STOCK_FREE:{
                freeVc = [YZMHCMInstance instanceWithControllerName:@"freeExperience"];
                [freeVc updateWithParamsManual:param];
                [YZMHCMInstance popViewController:freeVc animated:YES];
            }
                break;
                
            case YZM_TRADE_TYPE_FOR_A_STOCK_SIM:{
                simVC=[YZMHCMInstance instanceWithControllerName:@"Simulate"];
                [simVC updateWithParamsManual:param];
                [YZMHCMInstance popViewController:simVC animated:YES];
            }
                break;
                
            default:
                break;
        }
        
    }

}


#pragma mark -- ui

- (void)createObjects{
    
    self.navigationItem.titleView = [self titleView];
    self.bottomView = [UIView new];
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
    }];
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview: self.tableView];
    [self.tableView registerClass: [YZMyStocksSearchCell class] forCellReuseIdentifier: sYZMyStocksSearchCellID];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.contentInset = UIEdgeInsetsZero;
    
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.bottomView.mas_top);
    }];
    
    self.clearView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    self.clearView.backgroundColor = [YZMAppStyle colorForMain];
    UIButton *clearButton = [UIButton new];
    clearButton.titleLabel.font = [YZMAppStyle smallSizeFont];
    [clearButton setTitleColor: [YZMAppStyle colorForLightGrayText] forState: UIControlStateNormal];
    [clearButton setTitle: @"清除搜索历史记录" forState: UIControlStateNormal];
    [clearButton addTarget: self action: @selector(clearButtonPressed:) forControlEvents: UIControlEventTouchUpInside];
    [self.clearView addSubview: clearButton];
    [clearButton mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.right.centerY.equalTo(self.clearView);
        make.height.mas_equalTo(30);
    }];
}


- (UIView *)titleView{
    
    UIView *containView = [UIView new];
    containView.backgroundColor = [UIColor clearColor];
    containView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width- 30, 40);
    self.cancelButton = [UIButton buttonWithType: UIButtonTypeCustom];
    self.cancelButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.cancelButton setTitle: @"取消" forState: UIControlStateNormal];
    [self.cancelButton setTintColor:[YZMAppStyle colorForIconColor]];
    self.cancelButton.titleLabel.font = [YZMAppStyle largeSizeFont];
    [containView addSubview: self.cancelButton];
    [self.cancelButton addTarget: self action: @selector(cancelButtonPressed:) forControlEvents: UIControlEventTouchUpInside];
    
    [self.cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.centerY.equalTo(containView);
        make.top.bottom.equalTo(containView);
        make.right.equalTo(containView);
        make.width.mas_equalTo(44);
        make.height.mas_equalTo(44);
    }];
    
    self.searchField = [UITextField new];
    self.searchField.leftViewMode = UITextFieldViewModeAlways;
    self.searchField.placeholder = @"输入股票代码/名称/拼音";
    self.searchField.font = [YZMAppStyle mediumSizeFont];
    self.searchField.backgroundColor = [UIColor whiteColor];
    self.searchField.layer.cornerRadius = 2;
    self.searchField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.searchField addTarget:self action: @selector(textValueChanged:) forControlEvents: UIControlEventEditingChanged];
    self.searchField.inputView = self.inputView;
    self.searchField.inputAccessoryView = self.switchKeyBoardView;
    [containView addSubview: self.searchField];
    [self.searchField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(containView);
//        make.top.equalTo(containView.mas_top);
//        make.bottom.equalTo(containView.mas_bottom).with.offset(-8);
        make.height.mas_equalTo(30);
        make.left.equalTo(containView.mas_left);
        make.width.equalTo(@(ScreenWidth - 100));
        make.right.equalTo(self.cancelButton.mas_left).offset(-4);
    }];
    
    UIView *tempView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, 30, 30)];
    UIImageView *imageView = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"icon_gray_search"]];
    [tempView addSubview: imageView];
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(tempView);
    }];
    self.searchField.leftView = tempView;
    
    return containView;
}

#pragma mark -- init

- (void)updateWithParams: (NSDictionary *)params {
    
    self.tradeType = [params[@"tradeType"] integerValue];
    self.param = params;
    if (!self.tradeType) {
        
        self.tradeType = YZM_TRADE_TYPE_FOR_A_STOCK;
    }
}

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMyStocksAddViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

- (WclKeyBoardView *)keyBoardView{
    if (!_keyBoardView) {
        _keyBoardView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([WclKeyBoardView class]) owner:self options:nil][0];
        _keyBoardView.delegate = self;
        _keyBoardView.frame = CGRectMake(0, 0, ScreenWidth, 200);
    }
    return _keyBoardView;
}

- (UIView *)inputView{
    if (!_inputView) {
        _inputView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 200)];
        if (ScreenWidth > 375) {
            _inputView.frame = CGRectMake(0, 0, ScreenWidth, 258);
        }
        if (iPhoneX){
             _inputView.frame = CGRectMake(0, 0, ScreenWidth, 258 + 35);
        }
        [_inputView addSubview:self.keyBoardView];
        [self.keyBoardView mas_makeConstraints:^(MASConstraintMaker *make) {
            if (iPhoneX) {
                make.top.left.right.equalTo(_inputView);
                make.bottom.equalTo(self.inputView.mas_bottom).offset(-35);
            }else{
                 make.edges.equalTo(_inputView);
            }
           
        }];
    }
    return _inputView;
}

- (SwitchKeyBoardView *)switchKeyBoardView{
    if (!_switchKeyBoardView) {
        _switchKeyBoardView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([SwitchKeyBoardView class]) owner:self options:nil][0];
        _switchKeyBoardView.delegate = self;
    }
    return _switchKeyBoardView;
}

#pragma mark - SwitchKeyBoardViewDelegate

- (void)switchKeyBoardWith:(SwitchKeyBoardType)keyboardType{
    switch (keyboardType) {
        case SwitchKeyBoardTypeSystem:{
             self.switchKeyBoardView.switchTitle = customInputTitle;
            self.searchField.inputView = nil;
            [self.searchField reloadInputViews];
        }
         break;
        case SwitchKeyBoardTypeCustom:{
             self.switchKeyBoardView.switchTitle = systemInputTitle;
            self.searchField.inputView = self.inputView;
            [self.searchField reloadInputViews];
           
        }
            
        default:
            break;
    }
   
}

#pragma mark - WclKeyBoardViewDelegate
- (void)changeString:(NSString *)string{
    self.searchString = [NSMutableString stringWithString:[self.searchField.text stringByAppendingString:string]];
    self.searchField.text = self.searchString;
    [self searchString:self.searchString];
}

- (void)deleteString{
    if (self.searchString.length > 0) {
        [self.searchString deleteCharactersInRange:NSMakeRange(self.searchString.length - 1, 1)];
        self.searchField.text = self.searchString;
        [self searchString:self.searchString];
        return;
    }
}

- (void)searchString:(NSString *)string{
    NSString *inputStr = string;
    __weak typeof(&*self) safeSelf = self;
    if(inputStr.length > 0){
        [[YZMStockSearchService sharedService] fecthStocksWithInput:[string trimSpace] result:^(NSArray *results){
            
            safeSelf.dataList = results;
            safeSelf.tableView.tableFooterView = nil;
            safeSelf.isHistoryRecordFlag = NO;
            [safeSelf.tableView reloadData];
        }];
        
    }else{
        
        [[YZMStockSearchService sharedService] fecthHistoryResult: ^(NSArray *results) {
            
            safeSelf.dataList = results;
            safeSelf.isHistoryRecordFlag = YES;
            if (results.count == 0) {
                
                safeSelf.tableView.tableFooterView = nil;
            }else{
                safeSelf.tableView.tableFooterView = safeSelf.clearView;
            }
            
            [safeSelf.tableView reloadData];
        }];
    }
}

@end
